import React, { useState, useEffect } from "react";
import Taro from "@tarojs/taro";
import { View } from "@tarojs/components";
import { Button, Image, Checkbox } from "@nutui/nutui-react-taro";
// import { Checklist } from "@nutui/icons-react-taro";

import { getUserInfo } from "../../services/account";

import { wxLogin, getWxCode } from "../../utils/wxApi";
import { showErrorToast } from "../../utils/util";

import BindPhone from "../../components/modal/bind-phone";

import Logo from "../../assets/imgs/logo-login.svg";

import "./index.scss";

function Login() {
  const [isCheck, setIsCheck] = useState(false);
  const [showModal, setShowModal] = useState(0);

  // 获取-用户信息
  const postUserInfo = async () => {
    const res = await getUserInfo();
    // console.log(`res:${JSON.stringify(res)}`);
    Taro.setStorageSync("userInfo", res.data);
  };

  const postLogin = () => {
    if (!isCheck) {
      showErrorToast("请先阅读并勾选用户注册协议");
      return;
    }
    wxLogin()
      .then((res) => {
        // console.log(`Loginres====>>>${JSON.stringify(res)}`);
        const { status, token } = res;
        Taro.setStorageSync("token", token);
        if (status === 2) {
          // Taro.setStorageSync('token', loginRes.data.token);
          // Taro.removeStorageSync('token');
          // 拉起绑定手机号
          setShowModal(1);
          return;
        }
        postUserInfo();
        Taro.switchTab({
          url: "/pages/home/home",
        });
      })
      .catch(() => {
        // setGlobalData('hasLogin', false)
        // showErrorToast('微信登录失败');
        // Taro.switchTab({
        //   url: '/pages/index/index'
        // })
      });
  };

  return (
    <View className="g_login">
      <View className="login_hd">
        <Image className="logo" src={Logo} mode="aspectFit" />

        <View className="trip">欢迎使用霍尼韦尔软件平台</View>
      </View>
      <View className="login_bd">
        <Button
          type="primary"
          className="btn_login"
          // disabled={!isCheck}
          onClick={() => postLogin()}
        >
          登录
        </Button>
        <View className="agreement">
          <Checkbox
            className="agreement_check"
            label="用户注册协议"
            checked={isCheck}
            defaultChecked={isCheck}
            onChange={(checked) => {
              setIsCheck(checked);
            }}
          />
          {/* <Checkbox icon={<Checklist />}
              checkedIcon={<Checklist
                className="nut-checkbox__icon" />}>自定义图标</Checkbox> */}
        </View>
      </View>
      <View className="login_ft"></View>
      {showModal === 1 ? (
        <BindPhone
          show={showModal === 1}
          onClose={() => setShowModal(0)}
          onCall={() => {}}
        />
      ) : null}
    </View>
  );
}

export default Login;
